<?php

namespace zhtfrontend\controllers;

use common\models\datas\Balance;
use common\models\datas\BalanceRelation;
use common\models\datas\CardAttr;
use common\models\datas\CateAttr;
use common\models\datas\Classhourfee;
use common\models\datas\Customer;
use common\models\datas\Student;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use Yii;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\Mechanic;
use yii\helpers\Json;
use yii\data\Pagination;
use yii\web\Response;
use yii\helpers\ArrayHelper;
use common\components\extenders\AjaxObject;

class ClasshourController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $data = Classhourfee::find()->where(['site_id' => Fun::getSiteId()])->orderBy('class_date desc');
        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);

            if (isset($search_data['mechanic_id']) && $search_data['mechanic_id'] > 0) {
                $data->andWhere(['mechanic_id' => $search_data['mechanic_id']]);
            }
            if (isset($search_data['searchWay']) && $search_data['searchWay'] > 0) {
                if ($search_data['searchWay'] == 1) {
                    $data->andWhere(['between', 'created_at', strtotime(date('Y-m', strtotime($search_data['searchDate']))), strtotime(date('Y-m', strtotime("next month", strtotime($search_data['searchDate']))))]);
                } else {
                    $data->andWhere(['between', 'created_at', strtotime(date('Y-m-d', strtotime($search_data['searchDate']))), strtotime(date('Y-m-d', strtotime("+1 day", strtotime($search_data['searchDate']))))]);
                }
            }
            if (isset($search_data['state']) && $search_data['state'] > 0) {
                if ($search_data['state'] == 1) {
                    $data->andWhere(['status' => 1]);
                } else {
                    $data->andWhere(['status' => 0]);
                }
            }
        }

        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $array = Fun::asArray($model, ['checkbox']);
        $listData = Mechanic::find()->select(['name', 'id'])->indexBy('id')->column();
        return $this->render('index', ['listData' => $listData, 'data' => $array, 'pages' => $pages]);
    }

    /**
     *
     */
    public function actionBatchupdate()
    {
        if (\Yii::$app->request->isAjax) {
            $post = \Yii::$app->request->post();
            if (!empty($post['ids'])) {
                $ids = $post['ids'];
                $idsArr = explode(',', $ids);
                $items = Classhourfee::findAll($idsArr);
                $arr = [];
                foreach ($items as $val) {
                    $result = BalanceRelation::find()->where(['balance_id' => $val->id, 'type' => 1])->one();
                    if (empty($result)) {
                        $arr[] = $val->mechanic_id;
                    }
                }
                if ($arr) {
                    $newarr = array_unique($arr);
                    foreach ($newarr as $m_id) {
                        $price = 0;
                        foreach ($items as $item) {
                            $result = BalanceRelation::find()->where(['balance_id' => $m_id, 'type' => 1])->one();
                            if ($item->mechanic_id == $m_id && empty($result)) {
                                $price += $item->cost;
                            }
                            $admissionfee = Classhourfee::findOne(['id' => $item->id]);
                            $admissionfee->status = 1;
                            $admissionfee->save(false);
                        }
                        $model = new Balance();
                        $model->title = '';
                        $model->mechanic_id = $m_id;
                        $model->price = $price;
                        $model->user_id = \Yii::$app->user->id;
                        $model->created_at = time();
                        $model->updated_at = 0;
                        $model->voucher = '';
                        $model->type = 1;
                        $model->site_id = Fun::getSiteId();
                        $model->save(false);
                        if ($model->balance_id > 0) {
                            foreach ($items as $goods) {
                                $result = BalanceRelation::find()->where(['balance_id' => $goods->id, 'type' => 1])->one();
                                if ($goods->mechanic_id == $m_id && empty($result)) {
                                    $srModel = new BalanceRelation();
                                    $srModel->relation_id = $goods->id;
                                    $srModel->balance_id = $model->balance_id;
                                    $srModel->type = 1;
                                    $srModel->save(false);
                                }
                            }
                        }
                    }
                    return 1;
                }
                return 2;
            } else {
                return 3;
            }
        }

    }

    public function actionUpdatesign()
    {
        $cl = (new \yii\db\Query())
            ->select(['CONCAT(student_id,lesson_id) as sl'])
            ->from('{{%classhourfee}}')
            ->column(Fun::getSysDb());

        $check_list = (new \yii\db\Query())
            ->select(['sc.*', 'oi.mechanic_id', 'oi.goods_id', 'o.customer_id', 'cs.class_manage_id', 'CONCAT(sc.student_id,sc.class_lesson_id)'])
            ->from('{{%student_check}} sc')
            ->leftJoin('{{%orders_items}} oi', 'sc.order_sales_id = oi.id')
            ->leftJoin('{{%orders}} o', 'o.id = oi.orders_id')
            ->leftJoin('{{%class_student}} cs', 'cs.id = sc.class_student_id')
            ->andWhere(['sc.status' => 1])
            ->andWhere(['o.order_type' => 'appointment'])
            ->andWhere(['not in', 'CONCAT(sc.student_id,sc.class_lesson_id)', $cl])
            ->all(Fun::getSiteDb());
        if ($check_list) {
            foreach ($check_list as $check) {
                $row = Classhourfee::find()->where(['student_id' => $check['student_id'], 'lesson_id' => $check['class_lesson_id'], 'site_id' => Fun::getSiteId()])->one();
                if ($row == null) {
                    $mechanic = Mechanic::findOne($check['mechanic_id']);
                    $goods = Goods::findOne($check['goods_id']);
                    $classroom = GoodsAttr::find()->where(['goods_id' => $check['goods_id'], 'obj_type' => 'classroom_name'])->one();
                    $teacher = GoodsAttr::find()->where(['goods_id' => $check['goods_id'], 'obj_type' => 'teacher'])->one();
                    $class_lesson = ClassLesson::findOne($check['class_lesson_id']);
                    $class_count = ClassLesson::find()->where(['class_id' => $check['class_manage_id']])->count();
                    $customer = Customer::findOne($check['customer_id']);
                    $student = Student::find()->where(['id' => $check['student_id']])->one();

                    $cost = 0;
                    if (!empty($goods) && $class_count > 0) {
                        $cost = floor($goods->cost / $class_count);
                    }

                    $student_age = 0;
                    if (!empty($student) && $student->age != null) {
                        $student_age = date('Y') - $student->age;
                    }
                    $salesman = CardAttr::find()->where(['customer_id' => $check['customer_id']])->one();
                    $ClasshourfeeModel = new Classhourfee();
                    $ClasshourfeeModel->customer_id = $check['customer_id'];
                    $ClasshourfeeModel->student_id = $check['student_id'];
                    $ClasshourfeeModel->mechanic_id = $check['mechanic_id'];
                    $ClasshourfeeModel->class_id = $check['class_manage_id'];
                    $ClasshourfeeModel->class_student_id = $check['class_student_id'];
                    $ClasshourfeeModel->lesson_id = $check['class_lesson_id'];
                    $ClasshourfeeModel->goods_id = $check['goods_id'];
                    $ClasshourfeeModel->site_id = Fun::getSiteId();
                    $ClasshourfeeModel->created_at = time();
                    $ClasshourfeeModel->mechanic_name = !empty($mechanic) ? $mechanic->name : '';
                    $ClasshourfeeModel->goods_name = !empty($goods) ? $goods->name : '';
                    $ClasshourfeeModel->cost = $cost;
                    $ClasshourfeeModel->classroom_id = !empty($classroom) ? $classroom->attribute_id : 0;
                    $ClasshourfeeModel->classroom_name = !empty($classroom) ? $classroom->value : '';
                    $ClasshourfeeModel->teacher_id = !empty($teacher) ? $teacher->attribute_id : 0;
                    $ClasshourfeeModel->teacher_name = !empty($teacher) ? $teacher->value : '';
                    $ClasshourfeeModel->class_date = !empty($class_lesson) ? $class_lesson->class_date : 0;
                    $ClasshourfeeModel->class_day = !empty($class_lesson) ? date('w', $class_lesson->class_date) : 0;
                    $ClasshourfeeModel->class_start = !empty($class_lesson) ? $class_lesson->start_time : '';
                    $ClasshourfeeModel->class_end = !empty($class_lesson) ? $class_lesson->end_time : '';
                    $ClasshourfeeModel->customer_name = !empty($customer) ? $customer->name : '';
                    $ClasshourfeeModel->student_name = !empty($student) ? $student->name : '';
                    $ClasshourfeeModel->cate_id = !empty($goods) ? $goods->cat_id : 0;
                    $ClasshourfeeModel->mechanic_area = !empty($mechanic) ? $mechanic->region : '';
                    $ClasshourfeeModel->salesman_id = !empty($salesman) ? $salesman->salesman_id : 0;
                    $ClasshourfeeModel->student_age = $student_age;


                    $ClasshourfeeModel->save(false);
                }
            }
        }
        return $this->redirectMessage('更新成功', Fun::url(['orderstatistic/singe']));
    }


}
